<template>
  <div class="image-with-fallback" :style="{ width, height }">
    <img
      v-if="!loadError && !loading"
      :src="currentSrc"
      :alt="alt"
      :class="imageClass"
      @load="handleLoad"
      @error="handleError"
    />
    
    <div v-else-if="loading" class="image-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
    </div>
    
    <div v-else class="image-error">
      <el-icon><Picture /></el-icon>
      <span v-if="showErrorText">{{ errorText }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { Picture, Loading } from '@element-plus/icons-vue'
import { getProxiedImageUrl } from '@/utils/upload'
import { config } from '@/config'

interface Props {
  src: string
  alt?: string
  width?: string
  height?: string
  imageClass?: string
  showErrorText?: boolean
  errorText?: string
  fallbackSrc?: string
}

const props = withDefaults(defineProps<Props>(), {
  alt: '图片',
  width: '100%',
  height: '100%',
  imageClass: '',
  showErrorText: true,
  errorText: '加载失败',
  fallbackSrc: ''
})

const loading = ref(true)
const loadError = ref(false)
const retryCount = ref(0)
const maxRetries = 2

const currentSrc = computed(() => {
  if (!props.src) return ''
  
  if (retryCount.value === 0) {
    return getProxiedImageUrl(props.src)
  } else if (retryCount.value === 1) {
    // 第一次重试：尝试直接URL
    return props.src.startsWith('http') ? props.src : `${config.uploadBaseUrl}${props.src}`
  } else {
    // 第二次重试：使用fallback
    return props.fallbackSrc || ''
  }
})

const handleLoad = () => {
  loading.value = false
  loadError.value = false
}

const handleError = () => {
  if (retryCount.value < maxRetries) {
    retryCount.value++
    loading.value = true
    loadError.value = false
  } else {
    loading.value = false
    loadError.value = true
  }
}

const resetState = () => {
  loading.value = true
  loadError.value = false
  retryCount.value = 0
}

watch(() => props.src, resetState)

onMounted(() => {
  if (!props.src) {
    loading.value = false
    loadError.value = true
  }
})
</script>

<style scoped>
.image-with-fallback {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.image-loading,
.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
  font-size: 12px;
  gap: 4px;
}

.image-error {
  background: #fef0f0;
  color: #f56c6c;
}

.image-loading .el-icon,
.image-error .el-icon {
  font-size: 16px;
}
</style> 